package sjtu.ChatClient;

import org.jdom.Document;

import command.CommandConstants;

import genDoc.LogOutDocGen;
import genDoc.UpdateFriendListDocGen;
import genDoc.VideoAskResultDocGen;
import genDoc.VideoChatRequestDocGen;
import genDoc.VoiceAskResultDocGen;
import genDoc.VoiceChatRequestDocGen;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class FriendsActivity extends ListActivity {
	private int idx;// if the local user is requesting, idx points to the requested user in friend array
	private ProgressDialog progressDialog;
	private String from;// the requesting user
	private ArrayAdapter<String> adapter;
	private WakeLock wakeLock;
	
	// called when the activity is first created
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		wakeLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "VideoReceiverMainActivity");
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, StateManager.getManager().getFriends());
		setListAdapter(adapter);
	}
	
	public void onResume(){
		super.onResume();
		
		wakeLock.acquire();
		StateManager.getManager().setCurrentHandler(handler);
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, StateManager.getManager().getFriends());
		setListAdapter(adapter);
	}
	
	public void onPause(){
		super.onPause();
		wakeLock.release();
	}
	
	public void onDestroy(){
		super.onDestroy();
		String name = StateManager.getManager().getLocalUserName();
		if(name.equals("") == false){
			Document doc = LogOutDocGen.genDoc(name);
			StateManager.getManager().getDataSender().add(doc);
		}
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
			case HandlerConstants.VIDEO_CHAT_ASK:
				from = (String) msg.obj;
				showDialog(2);
				break;
			case HandlerConstants.VOICE_CHAT_ASK:
				from = (String) msg.obj;
				showDialog(1);
				break;
			case HandlerConstants.VOICE_CHAT_REQUEST_SUCCESS:
				// launch another activity
				progressDialog.dismiss();
				Intent intent = new Intent(FriendsActivity.this, VoiceChatActivity.class);
				intent.putExtra(CommandConstants.ATTR_USER_NAME, StateManager.getManager().getFriends()[idx]);
				startActivity(intent);
				break;
			case HandlerConstants.VOICE_CHAT_REQUEST_FAILED:
				progressDialog.dismiss();
				Toast.makeText(FriendsActivity.this, StateManager.getManager().getFriends()[idx] + " busy!", Toast.LENGTH_LONG).show();
				break;
			case HandlerConstants.VIDEO_CHAT_REQUEST_SUCCESS:
				// launch another activity
				progressDialog.dismiss();
				Intent intent1 = new Intent(FriendsActivity.this, VideoChatActivity.class);
				intent1.putExtra(CommandConstants.ATTR_USER_NAME, StateManager.getManager().getFriends()[idx]);
				startActivity(intent1);
				break;
			case HandlerConstants.VIDEO_CHAT_REQUEST_FAILED:
				progressDialog.dismiss();
				Toast.makeText(FriendsActivity.this, StateManager.getManager().getFriends()[idx] + " busy!", Toast.LENGTH_LONG).show();
				break;
			case HandlerConstants.UPDATE_FRIEND_LIST:
				//adapter.notifyDataSetChanged();
				adapter = new ArrayAdapter<String>(FriendsActivity.this, android.R.layout.simple_list_item_1, StateManager.getManager().getFriends());
				setListAdapter(adapter);
				break;
			default:
				break;
			}
		}
	};
	
	public void onListItemClick(ListView parent, View v, int position ,long id){
		idx = position;
		if(StateManager.getManager().getLocalUserName().equals(StateManager.getManager().getFriends()[idx]) == false){
			showDialog(0);
		}
	}
	
	protected Dialog onCreateDialog(int id){
		if(id == 0){
			final CharSequence [] items = {"Voice Chat", "Video Chat"};
			AlertDialog.Builder builder = new AlertDialog.Builder(FriendsActivity.this);
			builder.setTitle("Choose a way");
			builder.setCancelable(true);
			builder.setItems(items, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String from = StateManager.getManager().getLocalUserName();
					String to = StateManager.getManager().getFriends()[idx];
					Document doc =  null;
					// TODO Auto-generated method stub
					if(which == 0){
						// send voice chat request to server
						doc = VoiceChatRequestDocGen.genDoc(from, to);
					} else {
						// send video chat request to server
						doc = VideoChatRequestDocGen.genDoc(from, to);
					}
					
					StateManager.getManager().getDataSender().add(doc);
					progressDialog = ProgressDialog.show(FriendsActivity.this, "", "Requesting, please wait...", true);
				}
			});
			
			return builder.create();
		} else if(id == 1){
			// voice chat ask
			AlertDialog.Builder builder = new AlertDialog.Builder(FriendsActivity.this);
			builder.setMessage("Accept Voice Chat With " + from + "?");
			builder.setCancelable(false);
			builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					// launch another activity
					Document doc = VoiceAskResultDocGen.genDoc(from, StateManager.getManager().getLocalUserName(), true);
					StateManager.getManager().getDataSender().add(doc);
					Intent intent = new Intent(FriendsActivity.this, VoiceChatActivity.class);
					intent.putExtra(CommandConstants.ATTR_USER_NAME, from);
					startActivity(intent);
				}
			});
			builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Document doc = VoiceAskResultDocGen.genDoc(from, StateManager.getManager().getLocalUserName(), false);
					StateManager.getManager().getDataSender().add(doc);
				}
			});
			
			return builder.create();
		} else if(id == 2){
			AlertDialog.Builder builder = new AlertDialog.Builder(FriendsActivity.this);
			builder.setMessage("Accept Video Chat With " + from + "?");
			builder.setCancelable(false);
			builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					// launch another activity
					Document doc = VideoAskResultDocGen.genDoc(from, StateManager.getManager().getLocalUserName(), true);
					StateManager.getManager().getDataSender().add(doc);
					Intent intent = new Intent(FriendsActivity.this, VideoChatActivity.class);
					intent.putExtra(CommandConstants.ATTR_USER_NAME, from);
					startActivity(intent);
				}
			});
			builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Document doc = VideoAskResultDocGen.genDoc(from, StateManager.getManager().getLocalUserName(), false);
					StateManager.getManager().getDataSender().add(doc);
				}
			});
			
			return builder.create();
		}
		
		return null;
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.login_menu, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.refresh:
			Document doc = UpdateFriendListDocGen.genDoc();
			StateManager.getManager().getDataSender().add(doc);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
